<template>
  <div class="detail">
    <div class="back-arrow" @click="goBack">
      <Icon size="24" name="arrow-left"/>
    </div>
    <div class="product-container">
      <van-swipe class="product-swipe" :autoplay="0">
        <van-swipe-item>
          <VanImage
              class="product-img"
              :src="getProductImageUrl()"
              fit="contain"
              @click="showImage()"
          />
        </van-swipe-item>
        <van-swipe-item>
          <VideoPlayer :productId="parseInt(this.$route.params.id)"/>
        </van-swipe-item>
      </van-swipe>
      <van-overlay :show="show" @click="show = false">
        <div class="wrapper">
          <van-image :src="getProductImageUrl()" class="block" />
        </div>
      </van-overlay>
    </div>

    <div class="product-info">
      <p class="product-name">{{ product.productName }}</p>
      <div class="product-price-sold">
        <p class="product-price">
          <span class="currency">¥</span>
          <span class="price">{{ product.price }}</span>
        </p>
        <p class="product-sold">已售{{ product.sold }}</p>
      </div>
      <div class="divider"></div>
      <div class="sku-controller" @click="showSku = true">
        <Row>
          <Col span="4">
            <p class="left-text">规格</p>
          </Col>
          <Col span="18">
            <p>当前已选</p>
          </Col>
          <Col span="2">
            <Icon size="15" color="#808080" name="arrow"/>
          </Col>
        </Row>
      </div>
      <div class="common-controller">
        <Row>
          <Col span="4">
            <p class="left-text">服务</p>
          </Col>
          <Col span="18">
            <p>支持七天无理由退货</p>
          </Col>
          <Col span="2">
            <Icon size="15" color="#808080" name="arrow"/>
          </Col>
        </Row>
      </div>
      <div class="common-controller">
        <Row>
          <Col span="4">
            <p class="left-text">发货</p>
          </Col>
          <Col span="18">
            <p>付款后1天内发货</p>
          </Col>
          <Col span="2">
            <Icon size="15" color="#808080" name="arrow"/>
          </Col>
        </Row>
      </div>
      <div class="divider"></div>
      <div class="review-controller">
        <Row>
          <Col span="18">
            <span class="review">商品评价</span>
            <span class="num">({{ reviews.length }} 条评价)</span>
          </Col>
          <Col span="6" @click="viewAllReviews">
            <span class="left-text">查看更多</span>
            <Icon size="15" color="#808080" name="arrow"/>
          </Col>
        </Row>
        <div v-for="review in reviews.slice(0, 2)" :key="review.reviewId" class="content">
          <div class="review-header">
            <VanImage
                round
                width="3rem"
                height="3rem"
                :src="require('@/assets/backgrounds/user.jpg')"
            />
            <div class="info">
              <p class="review-name">{{ review.username }}</p>
              <p class="review-date">{{ review.createTime }}</p>
            </div>
            <div class="rating">
              <Rate v-model="review.rating" readonly size="13"/>
            </div>
          </div>
          <div class="review-text">{{ review.comment }}</div>
        </div>
      </div>
      <div class="divider"></div>
      <div class="introduction">
        <p class="introduction-text">商品介绍</p>
        <p class="product-description">{{ product.description }}</p>
      </div>
    </div>
    <div class="footer">
      <van-goods-action>
        <van-goods-action-icon icon="shop-o" text="店铺" @click="onClickIcon" color="#ee0a24"/>
        <van-goods-action-icon icon="chat-o" text="客服"/>
        <van-goods-action-icon icon="cart-o" text="购物车"/>
        <van-goods-action-button type="warning" text="加入购物车" @click="showSku = true"/>
        <van-goods-action-button type="danger" text="立即购买" @click="showSku = true"/>
      </van-goods-action>
    </div>
    <van-sku v-model="showSku" :sku="sku" :goods="goods" @add-cart="onAddCart" @buy-clicked="onBuyClicked"
             @stepper-change="onStepperChange" @sku-selected="getSelectedSku">
      <template #sku-header-price>
        <div class="van-sku__goods-price" v-if="cartTotalPrice !== 0">
          <span class="van-sku__price-symbol">￥</span>
          <span class="van-sku__price-num">{{ cartTotalPrice }}</span>
        </div>
      </template>
    </van-sku>
  </div>
</template>

<script>
import {
  Image as VanImage,
  GoodsAction as VanGoodsAction,
  GoodsActionIcon as VanGoodsActionIcon,
  GoodsActionButton as VanGoodsActionButton,
  Col, Row, Icon, Rate, Sku as VanSku,
  Swipe as VanSwipe, SwipeItem as VanSwipeItem,
    Toast,Overlay as VanOverlay
} from 'vant';
import http from "@/plugins/http";
import VideoPlayer from '@/views/template-views/VideoPlayer.vue'; // 引入视频播放器组件

export default {
  name: "PetView",
  components: {
    Icon,
    Row,
    Col,
    VanImage,
    VanGoodsAction,
    VanGoodsActionIcon,
    VanGoodsActionButton,
    Rate,
    VanSku,
    VideoPlayer,
    VanSwipe,
    VanSwipeItem,
    VanOverlay
  },
  data() {
    return {
      show: false,
      product: {},
      reviews: [],
      showSku: false,
      sku: {
        tree: [],
        list: [],
        price: '0.00',
        stock_num: 0,
      },
      goods: {
        title: '',
        picture: ''
      },
      selectedSku: {},
      cartTotalPrice: 0,
      cartQuantity: 1
    };
  },
  methods: {
    goBack() {
      localStorage.removeItem('productId');
      this.show=false;
      this.$router.go(-1);
    },
    onClickIcon() {

    },
    fetchProduct(productId) {
      http.get(`/product/${productId}`)
          .then(response => {
            this.product = response.data || {};
            this.setupSkuData();

            this.cartTotalPrice = this.sku.price;
          })
          .catch(error => {
            console.error("获取商品信息出错:", error);
          });
    },
    fetchReviews(productId) {
      http.get(`/review/product/${productId}`)
          .then(response => {
            console.log("Fetched reviews:", response.data);
            this.reviews = response.data || [];
          })
          .catch(error => {
            console.error("获取评价信息出错:", error);
          });
    },
    showImage() {
      this.show = true;
    },
    getProductImageUrl() {
      return this.product.imageUrl
          ? require('@/' + `${this.product.imageUrl}`)
          : require('@/assets/products/default.png');
    },
    saveProductIdToLocalStorage(productId) {
      localStorage.setItem('productId', productId);
    },
    getProductIdFromLocalStorage() {
      return localStorage.getItem('productId');
    },
    viewAllReviews() {
      console.log("商品ID:", this.product.productId);
      this.$router.push({name: 'AllReviews', params: {id: this.product.productId}});
    },
    setupSkuData() {
      console.log(this.product)
      this.goods.title = this.product.productName;
      this.goods.picture = this.getProductImageUrl();
      const productType = parseInt(this.product.type, 10); // 将字符串解析为整数
      if (productType=== 0) {
        this.sku.tree = [
          {
            k: '性别',
            v: [
              {id: '1', name: '公'},
              {id: '2', name: '母'}
            ],
            k_s: 's1'
          },
          {
            k: '品种',
            v: [
              {id: '1', name: '串种'},
              {id: '2', name: '纯种'}
            ],
            k_s: 's2'
          }
        ];

        this.sku.list = [
          {id: 1, s1: '1', s2: '1', price: this.product.price * 100, stock_num: this.product.stock},
          {id: 2, s1: '1', s2: '2', price: (this.product.price + 100) * 100, stock_num: this.product.stock},
          {id: 3, s1: '2', s2: '1', price: (this.product.price + 50) * 100, stock_num: this.product.stock},
          {id: 4, s1: '2', s2: '2', price: (this.product.price + 150) * 100, stock_num: this.product.stock}
        ];
      } else {
        // 默认规格设置
        this.sku.tree = [
          {
            k: '颜色',
            v: [
              {id: '1', name: '黑色'},
              {id: '2', name: '蓝色'}
            ],
            k_s: 's1'
          },
          {
            k: '尺寸',
            v: [
              {id: '1', name: '小'},
              {id: '2', name: '中'},
              {id: '3', name: '大'}
            ],
            k_s: 's2'
          }
        ];
        this.sku.list = [
          {id: 1, s1: '1', s2: '1', price: 100 * 100, stock_num: 10},
          {id: 2, s1: '1', s2: '2', price: 110 * 100, stock_num: 20},
          {id: 3, s1: '1', s2: '3', price: 120 * 100, stock_num: 30},
          {id: 4, s1: '2', s2: '1', price: 130 * 100, stock_num: 40},
          {id: 5, s1: '2', s2: '2', price: 140 * 100, stock_num: 50},
          {id: 6, s1: '2', s2: '3', price: 150 * 100, stock_num: 60}
        ];
      }

      this.sku.price = this.product.price;
      this.sku.stock_num = this.product.stock;
    },
    onAddCart() {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      const orderData = {
        userName: storedUser,
        productName: this.product.productName, // 商品名称
        type: "12",
        typeNames: this.getSelectedSkuText(),
        supplierName: this.product.supplier.supplierName,
        price: this.cartTotalPrice / this.cartQuantity, // 商品价格
        quantity: this.cartQuantity,// 商品数量
        imageUrl: this.product.imageUrl,
        productId: this.product.productId,
        stock_num: this.product.stock_num,
        description: this.product.description,
      };
      if (storedUser) {
        http.post('/cart/add', orderData)
            .then(() => {
              Toast.success("添加购物车成功");
              this.$router.push('/CartView');
            })
            .catch(error => {
              console.error("添加订单失败:", error);
              Toast.fail("添加购物车失败");
            });
        console.log("传递参数:", orderData);
      } else {
        Toast.fail("请先登录");
        this.$router.push('/');
      }
    },
    onBuyClicked() {
      const product = {
        cartId:0,
        productName: this.product.productName,
        skuDescription: this.getSelectedSkuText(),
        price: this.cartTotalPrice / this.cartQuantity,
        quantity: this.cartQuantity,
        imgUrl: this.getProductImageUrl(),
        stock_num: this.product.stock,
        productId: this.product.productId
      };

      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if (storedUser) {
        this.$router.push({name: 'OrderView', params: {orderData: [product]}});
        console.log("传递参数:", [product]);
      } else {
        Toast.fail("请先登录");
        this.$router.push('/');
      }
    },
    getSelectedSkuText() {
      const selectedSkuText = this.sku.tree.map(item => {
        const selectedValue = this.selectedSku.selectedSku[item.k_s];
        const selectedOption = item.v.find(option => option.id === selectedValue);
        return selectedOption ? selectedOption.name : '';
      });
      return selectedSkuText.join(' ');
    },
    onStepperChange(value) {
      this.cartQuantity = value;
      this.updateCartTotalPrice();
    },
    getSelectedSku(selectedSku) {
      this.selectedSku = selectedSku;
      this.updateCartTotalPrice();
    },
    updateCartTotalPrice() {
      const selectedSkuComb = this.selectedSku.selectedSkuComb;
      if (selectedSkuComb) {
        this.cartTotalPrice = (selectedSkuComb.price / 100) * this.cartQuantity;
      } else {
        this.cartTotalPrice = this.sku.price;
      }
    },
  },
  activated() {
    let productId = this.$route.params.id;
    if (productId) {
      this.saveProductIdToLocalStorage(productId);
    } else {
      productId = this.getProductIdFromLocalStorage();
      if (!productId) {
        console.error("未找到商品ID");
        return;
      }
    }
    this.fetchProduct(productId);
    this.fetchReviews(productId);

  }
};
</script>

<style scoped>
.detail {
  background-color: #cccccc;
  margin-bottom: 100px;
  position: relative; /* 让内容与箭头同级显示 */
}

.product-img {
  width: 100%;
  height: 30vh;
}

.product-info {
  background-color: #ffffff;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
}

.product-name {
  padding-top: 10px;
  font-weight: bold;
  font-size: 20px;
  padding-left: 20px;
}

.product-price-sold {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  margin-top: 10px;
}

.product-price {
  display: flex;
  align-items: center;
}

.currency {
  color: #f85f0c;
  font-weight: bold;
  font-size: 20px;
}

.price {
  color: #f85f0c;
  font-weight: bold;
  font-size: 30px;
}

.product-sold {
  display: flex;
  align-items: center;
  color: #888888;
  font-size: 14px;
}

.product-description {
  padding-top: 10px;
  padding-left: 20px;
  padding-right: 20px;
}

.common-controller {
  padding-left: 20px;
  font-size: 14px;
  padding-top: 15px;
}

.review-controller {
  padding-top: 10px;
  padding-left: 20px;
  font-size: 14px;
}

.left-text {
  color: #999987;
}

.review {
  font-weight: bold;
  font-size: 17px;
}

.num {
  color: #999987;
}

.divider {
  height: 5px;
  background-color: #f5f5f5;
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 10px;
  border-radius: 10px;
}

.review-header {
  margin-top: 10px;
  display: flex;
  align-items: flex-end;
  margin-bottom: 10px;
}

.info {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
}

.review-name {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.review-text {
  margin-bottom: 10px;
}

.content {
  margin-bottom: 10px;
  margin-right: 20px;
}

.rating {
  padding-left: 40px;
  padding-bottom: 23px;
}

.introduction-text {
  padding-top: 10px;
  padding-left: 20px;
  font-weight: bold;
  font-size: 17px;
}

.sku-controller {
  padding-left: 20px;
  font-size: 14px;
  padding-top: 10px;
}

.back-arrow {
  position: fixed; /* 固定在左上角 */
  top: 20px;
  left: 20px;
  z-index: 999; /* 确保箭头在最前面 */
  cursor: pointer; /* 鼠标移上去显示手型 */
  color: #ffffff;
}

.product-container {
  width: 100%;
  height: 300px; /* 设置容器的高度，可以根据需要调整 */
}

.product-swipe {
  width: 100%;
  height: 100%; /* 设置轮播容器的高度，与父容器一致 */
}


.product-swipe .product-img {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 图片适应方式，根据需要调整 */
}

.product-swipe video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.block {
  width: auto;
  height: auto;
  max-width: 90%;
  max-height: 90%;
}

</style>